import HttpService from '../../service/HttpService'
import ApiUrl from '../../service/ApiUrl'
import Vue from 'vue'
import Util from '../../service/Util'
import { Cart } from '../../service/Storage'

// Type config
const Types = {
	GET_CART: 'GET_CART',
	ADD_CART_COUNT: 'ADD_CART_COUNT',
	DELETE_CART_COUNT: 'DELETE_CART_COUNT'
}

// init state
const state = {
    cart: [],
    cartCount: 0
}

const getters = {
    cart: state => state.cart,
    cartCount: state => state.cartCount
}

// action
const actions = {
	getCarts({commit, state}){
		commit( Types.GET_CART)
	},
	addCart({commit,state}, item){
		Cart.add({
			id:item.id,
			name: item.name
		});
		commit( Types.GET_CART)
	},
	deleteCart({commit,state}, item){
		Cart.delete(item);
		commit( Types.GET_CART)
	},
	addOrDelCart({commit,state}, item ){
		if( Cart.isExsit(item) ){
			Cart.delete(item)
			commit( Types.DELETE_CART_COUNT , { item } )
		}else{
			Cart.add(item)
			commit( Types.ADD_CART_COUNT, { item } )
		}
		commit( Types.GET_CART )
	}
}

// init mutations 
const mutations = {
	[Types.GET_CART] ( state ){
		let cart = Cart.get()
		state.cart = cart;
		state.cartCount = cart.length;
	},
	[Types.ADD_CART_COUNT] ( state, { item } ){
		item.selected = true;
	},
	[Types.DELETE_CART_COUNT] ( state, { item } ){
		item.selected = false;
	}
}

export default {
  state,
  getters,
  actions,
  mutations
}